<template>
  <div v-loading="loading">
    <div
      class="echart"
      ref="pie"
      style="width: 100%;height: 610px;"
    ></div>
  </div>
</template>

<script>
import * as echarts from "echarts";
import theme from "@/assets/vintage.json";
import axios from "@/util/AxiosUtil";
import apis from "@/util/ApiUrls";
export default {
  name: "CategoryComponent",
  created() {
    // 注册主题-JSON主题方式
    echarts.registerTheme("vintage", theme);
    // 监听分类管理组件的删除事件
    this.$EventBus.$on("pie_category_changed", () => {
      // 刷新数据
     this.getData(this.refreshData);
    })
  },
  mounted() {
    this.getData(this.initChart);
  },
  methods: {
    // 获取数据
    getData(initFunc) {
      // 请求用户的分类以及对应的笔记数量信息
    axios
      .get(apis.api_article.categoryGroup)
      .then((res) => {
        let list = res.data;
        let chartData = [];
        // 构造数据
        list.forEach((element) => {
          chartData.push({
            name: element.categoryName,
            value: element.noteCount,
          });
        });
        // 初始化饼图
        initFunc(chartData);
      })
      .catch((e) => {
        this.$notify({
          title: "警告",
          message: "分类图获取失败:" + e.msg,
          type: "warning",
          position: 'bottom-right',
          duration: 1500,
        });
        this.$refs.pie.innerHTML =
          '<div style="position: relative;top:40%">分类图获取失败<div>';
        this.loading = false;
      });
    },
    // 初始化饼图
    initChart(chartData) {
      let chart = echarts.init(this.$refs.pie, "vintage", {
        height: "610px",
      });

      this.options.series[0].data = chartData;
      chart.setOption(this.options);
      // 绑定自适应事件 - 事件只绑定一次
      window.onresize = () => {
        console.log("window resized...");
        chart.resize();
      };

      // 解除加载状态
      this.loading = false;
      this.chart = chart;
    },
    // 刷新数据
    refreshData(chartData) {
      this.options.series[0].data = chartData;
      this.chart.setOption(this.options);
    },
  },
  data() {
    return {
      chart: undefined,
      loading: true,
      options: {
        tooltip: {
          trigger: "item",
        },
        legend: {
          // 底部类别超过数量时滚动
          type: "scroll",
          orient: "horizontal",
          bottom: 5,
        },
        series: [
          {
            name: "笔记分类",
            type: "pie",
            stillShowZeroSum: false, // 数据为0时显示饼图 - false: 不显示
            label: {
              show: false, // 数据为0显示标签 - false: 不显示
            },
            radius: "60%",
            data: [],
          },
        ],
      }
    };
  },
};
</script>

<style scoped>
.el-loading-spinner {
  margin-top: 40% !important;
}
</style>
